<?php
namespace app\common\tool;

class PickUpCode extends Base {
	protected $salt = 'ADid##cc!!';

	//生成核销码
	public function generate_code($oid) {
		$time = time() + 7200;
		$code = substr(md5(md5($oid . $time) . $this->salt), -6);
		return compact('code', 'time');
	}

	
	//获取核销码
	public function get_code($oid) {
		$redis = loader()->loadAny('redis', 'Redis');
		$result = $redis->getArray('pick_up_code_' . $oid);
		if($result && $result['time'] > time()) {
			return $result;
		} else {
			return $this->get_code_ipl($oid);
		}
	}

	//不读取缓存直接获取核销码
	public function get_code_ipl($oid) {
		$result = $this->generate_code($oid);
		$time = $result['time'];
		$code = $result['code'];
		$redis = loader()->loadAny('redis', 'Redis');
		$url = $this->generate_qr_code($oid, $code);
		$fullurl = loader()->loadAny('request', 'Base')->domain() . $url;
		$result['url'] = $url;
		$result['fullurl'] = $fullurl;
   		$redis->setArray('pick_up_code_' . $oid, $result, 86400);
   		return $result;
	}

	//生成二维码
	public function generate_qr_code($oid, $code) {
		$qrCode = \Endroid\QrCode\QrCode::create($oid . '__' . $code)
            ->setSize(300)
            ->setMargin(10);

        $writer = new \Endroid\QrCode\Writer\PngWriter();

        $savePath = ROOT_PATH . 'public/uploads/qrcodes/';
        if (!is_dir($savePath)) {
            mkdir($savePath, 0777, true);
        }
        $fileName = 'pickup_' . $oid . '.png';
        $fullPath = $savePath . $fileName;
        // 保存二维码到指定路径
        $result = $writer->write($qrCode);
        $result->saveToFile($fullPath);
        // 返回保存后的二维码相对路径
        return '/uploads/qrcodes/' . $fileName;
	}

	//验证核销码是否正确
	public function validate_code($oid, $code) {
		$redis = loader()->loadAny('redis', 'Redis');
		$result = $redis->getArray('pick_up_code_' . $oid);
		if(empty($result)) {
			return false;
		}
		if($code != $result['code'] || $result['time'] + 0 < time()) {
			return false;
		}
		return true;
	}
}
